// pages/goods_detail/goods_buy/goods_buy.js
var app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    goodsInfo: {
      type: Object,
      value: {},
      observer: function (newVal, oldVal) {
        if (newVal) {
          var goods_type = 0;
          if (newVal.group_type == 1) { //免费兑换
            goods_type = 2;
          } else if (newVal.group_type == 2) {  //免费拼团
            goods_type = 3;
          }
          this.setData({
            goods_type: goods_type,
          })
          if (goods_type == 0) {
            this.calcPrice(newVal.goods_stars_price, this.data.goods_num);
          } else if (goods_type == 2) {
            this.calcPrice(newVal.star_price, this.data.goods_num);
          } else if (goods_type == 3) {
            this.calcPrice(newVal.spell_stars, this.data.goods_num);
          }
        }
      }
    },
  },

  /**
   * 组件的初始数message
   */
  data: {
    goods_type: 0, //0表示换购，2表示兑换，3表示开团
    goods_num: 1
  },
  attached: function () {
    var pageHeight = app.globalData.pageHeight;
    var popHeight = (pageHeight - 330 + 52) / app.globalData.pixelRatio;
    var scrollViewHeight = pageHeight - 330 - 168 - 108;
    this.setData({
      popHeight: popHeight,
      scrollViewHeight: scrollViewHeight,
    })
    this.SKUConfirm();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 减少商品数量
     */
    goods_num_reduce: function () {
      var goods_num = this.data.goods_num - 1;
      if (goods_num > 0) {
        this.calcPrice(this.data.unit_price, goods_num);
      }
    },
    /**
     * 增加商品数量
     */
    goods_num_add: function () {
      var goods_num = this.data.goods_num + 1;
      this.calcPrice(this.data.unit_price, goods_num);
    },
    /**
     * SKU选择
     */
    selectSKU: function (e) {
      var attrIdx = e.currentTarget.dataset.attridx;
      var valueIdx = e.currentTarget.dataset.valueidx;
      var valueId = e.currentTarget.dataset.valueid;
      var goodsInfo = this.data.goodsInfo;
      goodsInfo.attr[attrIdx].selectedIdx = valueIdx;
      goodsInfo.attr[attrIdx].selectedId = valueId;
      this.setData({
        goodsInfo: goodsInfo,
      })
      this.SKUConfirm();
    },

    /**
     * SKU确认
     */
    SKUConfirm: function (succ, fail) {
      //检查是否所有sku项都已经选择
      var canSubmit = true;
      var err_msg = '';
      var gavids = "";    //选择属性的id集合链
      var selectedAttr = '';  //已选属性
      var unselectAttr = ''; //未选属性
      var goodsInfo = this.data.goodsInfo;
      for (var i = 0; i < goodsInfo.attr.length; i++) {
        var selectedIdx = goodsInfo.attr[i].selectedIdx;
        if (selectedIdx != null) {
          gavids += goodsInfo.attr[i].selectedId + ",";
          selectedAttr += "'" + goodsInfo.attr[i].attrValue[selectedIdx].name + "'，";
        } else {
          if (canSubmit) {
            err_msg = '请选择商品的' + goodsInfo.attr[i].name + '！';
            canSubmit = false;
          }
          unselectAttr += goodsInfo.attr[i].name + '，';
        }
      }

      // console.log(goodsInfo)
      var skuCover = goodsInfo.images.length > 0 ? goodsInfo.images[0] : '';
      if (canSubmit) {
        //修改SKU选择的显示信息
        selectedAttr = '已选择：' + selectedAttr.substring(0, selectedAttr.length - 1);
        //确定SKU参数
        gavids = gavids.substring(0, gavids.length - 1);
        this.sku_id = '';
        for (var i = 0; i < goodsInfo.skus.length; i++) {
          if (gavids == goodsInfo.skus[i].gavids) {
            this.sku_id = goodsInfo.skus[i].sku_id;
            this.stock = goodsInfo.skus[i].stock;
            skuCover = goodsInfo.skus[i].image;
            if (this.data.goods_type == 0) {
              this.calcPrice(goodsInfo.skus[i].goods_stars_price, this.data.goods_num);
            } else if (this.data.goods_type == 2) {
              this.calcPrice(goodsInfo.skus[i].star_price, this.data.goods_num);
            } else {
              this.calcPrice(goodsInfo.spell_stars, this.data.goods_num);
            }
            break;
          }
        }
        this.setData({
          skuCover: skuCover,
          skuInfo: selectedAttr,
        })
        if (this.sku_id != '') {
          typeof succ == 'function' && succ();
        } else {
          typeof fail == 'function' && fail('暂无库存！');
        }
      } else {
        //修改SKU选择的显示信息
        unselectAttr = '请选择：' + unselectAttr.substring(0, unselectAttr.length - 1);
        this.setData({
          skuCover: skuCover,
          skuInfo: unselectAttr,
        })
        //失败返回函数
        typeof fail == 'function' && fail(err_msg);
      }

    },

    /**
     * 价格计算
     */
    calcPrice: function (unit_price, goods_num) {
      goods_num = parseInt(goods_num);
      if (this.stock != null) {
        this.stock = parseInt(this.stock);
        if (this.stock == 0) {
          this.sku_id = '';
          this.Toast('暂无库存！');
          goods_num = this.stock;
        } else {
          if (goods_num == 0) {
            goods_num = 1;
          }
          if (goods_num > this.stock) {
            this.Toast('超过购买上限数量');
            goods_num = this.stock;
          }
        }
      }
      unit_price = parseFloat(unit_price);
      goods_num = parseInt(goods_num);
      var price = unit_price * goods_num;
      price = Math.round(price * 100) / 100;
      if (this.data.goods_type == 0) {
        price = '￥' + price;
      } else {
        price += '星星';
      }
      this.setData({
        unit_price: unit_price,
        goods_num: goods_num,
        price: price
      })
    },

    /**
     * 确定购买
     */
    submit: function () {
      this.SKUConfirm(() => {
        //兑换、玩购进入订单页面；拼团则进行开团操作
        if (this.data.goods_type != 3) {
          var pages = getCurrentPages();
          var currentPage = pages[pages.length - 1];
          var pageDeep = currentPage.route.split('/').length - 1;
          var url = 'pages/order/goods_order/goods_order?goods_id=' + this.data.goodsInfo.goods_id + '&sku_id=' + this.sku_id + "&goods_num=" + this.data.goods_num + "&goods_type=" + this.data.goods_type;
          for (var i = 0; i < pageDeep;i++) {
            url = '../' + url;
          }
          wx.navigateTo({
            url: url,
          })
        } else {
          this.groupExchange();
        }
      }, err_msg => {
        this.Toast(err_msg);
      })
    },

    /**
     * 免费开团
     */
    groupExchange: function () {
      if (this.groupIsCreating) {
        return;
      }
      this.groupIsCreating = true;
      setTimeout(() => {
        this.groupIsCreating = false;
      }, 1000);

      app.Ajax({
        url: '/api/index.php?app=group&act=create',
        method: 'POST',
        data: {
          goods_id: this.data.goodsInfo.goods_id,
          sku_id: this.sku_id
        },
        success: (res) => {
          wx.navigateTo({
            url: '../../pages/activity/group_exchange/group_info/group_info?spell_group_id=' + res.spell_group_id,
          })
        },
        fail: (err) => {
          this.Toast(err);
        }
      })
    },

    /**
     * 取消购买
     */
    buyCancel: function () {
      this.triggerEvent('cancel', {}, {})
    },
    /**
     * 显示报错信息
     */
    Toast: function (message) {
      this.setData({
        message: message,
      })
    },
  }
})
